package eip.chapter1.example.mediator;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.xml.stream.XMLStreamException;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.synapse.MessageContext;
import org.apache.synapse.Mediator;
import org.dom4j.Document;
import org.dom4j.io.XMLWriter;

import eip.chapter1.example.CSVToXMLTransformer;

/**
 * A simple mediator that takes a CSV String and transforms
 * it to an XML file. This is not a generic mediator and
 * only useful for this example.
 * 
 * @author nl24167
 */
public class CSVToXMLMediator implements Mediator {

	public boolean mediate(MessageContext msgContext)  {
		CSVToXMLTransformer transformer = new CSVToXMLTransformer();
		OMElement element = msgContext.getEnvelope().getBody().getFirstElement();
		Document result = transformer.transformCSV(element.getText());
		
		ByteArrayOutputStream bOut = new ByteArrayOutputStream();
		XMLWriter writer = new XMLWriter();
		try {
			writer.setOutputStream(bOut);
			writer.write(result);
			StAXOMBuilder builder = new StAXOMBuilder(new ByteArrayInputStream(bOut.toByteArray()));
			msgContext.getEnvelope().getBody().setFirstChild(builder.getDocumentElement());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XMLStreamException e) {
			e.printStackTrace();
		}
		
		return true;
	}

	public String getType() {
		return "CSVToXMLMediator";
	}

}
